﻿using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.UI.WebControls;

namespace MyLib.Web.UI {
	/// <summary>
	/// 
	/// </summary>
	public class MyViewStateParameter : Parameter {
		/// <summary>
		/// 
		/// </summary>
		private static readonly PropertyInfo m_viewStatePropertyInfo = typeof(System.Web.UI.Page)
			.GetProperty("ViewState", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

		/// <summary>
		/// 
		/// </summary>
		public string Key { get; set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="control"></param>
		/// <returns></returns>
		protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control) {
			var p0 = Expression.Parameter(typeof(System.Web.UI.Page));
			var exp = Expression.Lambda<Func<System.Web.UI.Page, System.Web.UI.StateBag>>(
				Expression.Property(
					p0,
					m_viewStatePropertyInfo),
				p0).Compile();

			return exp(control.Page)[Key];
		}

		/// <summary>
		/// 
		/// </summary>
		/// <returns></returns>
		protected override Parameter Clone() {
			var ret = new MyViewStateParameter();
			ret.Name = Name;
			ret.Size = Size;
			ret.Type = Type;
			ret.ConvertEmptyStringToNull = ConvertEmptyStringToNull;
			ret.DbType = DbType;
			ret.DefaultValue = DefaultValue;
			ret.Direction = Direction;
			ret.Key = this.Key;
			return ret;
		}
	} // end of MyViewStateParameter.
}
